package com.studentstreet.tools.dbhelper;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.studentstreet.entities.CommentEntity;

public class CommentDBHelper {
	private DBHelper dbHelper = null;

	public CommentDBHelper(Context context) {
		super();
		dbHelper = new DBHelper(context);
	}

	public long saveToDB(String json) {
		List<CommentEntity> commentList = new ArrayList<CommentEntity>();
		Gson gson = new Gson();
		Type listType = new TypeToken<ArrayList<CommentEntity>>() {
		}.getType();
		commentList = gson.fromJson(json, listType);
		return saveToDB(commentList);
	}

	public long saveToDB(List<CommentEntity> commentList) {
		long row = 0L;
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		for (CommentEntity comment : commentList) {
			db.delete(DBTools.TABLE_COMMENT, DBTools.COMMENT_ID + " = "
					+ comment.getId(), null);
			ContentValues values = new ContentValues();
			values.put(DBTools.COMMENT_ID, comment.getId());
			values.put(DBTools.COMMENT_GID, comment.getGoods_id());
			values.put(DBTools.COMMENT_CONTENT, comment.getContent());
			values.put(DBTools.COMMENT_RANK, comment.getRank());
			values.put(DBTools.COMMENT_TIME, comment.getTime());
			values.put(DBTools.COMMENT_TITLE, comment.getTitle());
			values.put(DBTools.COMMENT_UID, comment.getUser_id());
			row += db.insert(DBTools.TABLE_COMMENT, null, values);
		}
		db.close();
		return row;
	}
}
